package com.tg.app.activity.device.add;

import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.appbase.custom.base.UDPDevice;
import com.tange.base.toolkit.WifiAp;
import com.appbase.custom.constant.CommonConstants;
import com.base.BaseFragment;
import com.tange.module.add.bind.DeviceBinding;
import com.tange.module.add.wifi.DeviceWiFiConfiguration;
import com.tange.module.camera.hub.CameraHub;
import com.tg.app.R;
import com.tg.app.adapter.WifiListAdapter;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tg.app.listener.OnAddDeviceListener;
import com.tg.app.util.LogUtils;
import com.tange.base.toolkit.PreferenceUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tange.base.toolkit.TGThreadPool;

import com.tg.data.http.entity.BindDeviceBean;
import com.tg.network.socket.TGUDPSocket;
import com.tg.network.socket.UDPLanSocket;
import com.tg.network.socket.UDPWifiSocket;

import java.util.ArrayList;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SearchConnectFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SearchConnectFragment extends BaseFragment implements View.OnClickListener, WifiListAdapter.OnAddWifiDeviceClickListener {
    public static final String TAG = "SearchConnectFragment";

    private OnAddDeviceListener listener;
    private TextView tvTips, tvWifiNum;
    private ListView listView;
    private ArrayList<String> list;
    private int originType;
    private Camera camera;
    private LinearLayout llSetWifiLayout;
    private EditText edtWifiName;
    private EditText edtWifiPwd;
    private CheckBox pwdCheckBox;
    private Button btnSendWifi;
    private String bind_token;
    private ImageView ivClear;
    private TGUDPSocket udpSocket;
    private WifiListAdapter adapter;
    private static final int SEARCH = 0x01;
    private WifiAp wifiAp;
    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == SEARCH) {
                if (udpSocket != null) {
                    udpSocket.stopUDPSocket();
                }
            }
            return false;
        }
    });

    public void setListener(OnAddDeviceListener listener) {
        this.listener = listener;
    }

    public SearchConnectFragment() {
    }

    // TODO: Rename and change types and number of parameters
    public static SearchConnectFragment newInstance(Bundle args) {
        SearchConnectFragment fragment = new SearchConnectFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            list = getArguments().getStringArrayList(LanSearchFragment.EXT_LAN_SEARCH_RESULT);
            originType = getArguments().getInt(AddFragmentTabActivity.EXT_DEVICE_ADD_TYPE, 0);
            if (originType == AddFragmentTabActivity.DEVICE_ADD_TYPE_AP) {
               // camera = TGApplicationBase.getApplication().getCurCamera();
            } else {
                if (originType  == AddFragmentTabActivity. DEVICE_ADD_TYPE_LAN){
                    udpSocket = new UDPLanSocket(getContext());
                }else {
                    udpSocket = new UDPWifiSocket(getContext());
                }

                udpSocket.setOnReceiveUDPSocketLister(new UDPWifiSocket.OnReceiveUDPSocketLister() {
                    @Override
                    public void onReceive(final UDPDevice device) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (!list.contains(device.sn) && device.state == 0) {
                                    list.add(device.sn);
                                }
                                adapter.notifyDataSetChanged();
                                if (isAdded()) {
                                    tvWifiNum.setText(String.format(getString(R.string.search_wifi_device_num), list.size()));
                                }
                            }
                        });


                    }
                });
                udpSocket.startUDPSocket();
                udpSocket.startSearchDevice();
                //搜索20秒
                handler.sendEmptyMessageDelayed(SEARCH, 1000 * 30);
            }
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (originType == AddFragmentTabActivity.DEVICE_ADD_TYPE_AP || originType == AddFragmentTabActivity.DEVICE_ADD_TYPE_AP_LOCAL) {
            tvTips.setText(R.string.search_connect_tips_ap);
        } else {
            tvTips.setText(R.string.search_connect_tips_lan);
            llSetWifiLayout.setVisibility(View.GONE);
        }

        adapter = new WifiListAdapter(list, getContext(), this, originType);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            String name = "";
            if (originType == AddFragmentTabActivity.DEVICE_ADD_TYPE_AP) {
                wifiAp = JSON.parseObject(list.get(position), WifiAp.class);
                name = wifiAp.ssid;
                TGLog.i(TAG, "OnItemClickListener: " + list.get(position));
                if (wifiAp != null && wifiAp.enctype != 1) {
                    btnSendWifi.setEnabled(false);
                } else {
                    btnSendWifi.setEnabled(true);
                }
            } else {
                name = list.get(position);
                btnSendWifi.setEnabled(true);
            }
            edtWifiName.setText(name);

        });
        pwdCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    edtWifiPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    edtWifiPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                int position = edtWifiPwd.getText().toString().trim().length();
                if (position > 0) {
                    edtWifiPwd.setSelection(position);
                }
            }
        });
        listView.setVisibility(View.VISIBLE);
        edtWifiPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(editable.toString())) {
                    ivClear.setVisibility(View.GONE);
                    if (originType == AddFragmentTabActivity.DEVICE_ADD_TYPE_AP) {
                        if (wifiAp != null && wifiAp.enctype != 1) {
                            btnSendWifi.setEnabled(false);
                        } else {
                            btnSendWifi.setEnabled(true);
                        }
                    }
                } else {
                    btnSendWifi.setEnabled(true);
                    ivClear.setVisibility(View.VISIBLE);
                }
            }
        });
        edtWifiName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(editable.toString())) {
                    btnSendWifi.setEnabled(false);
                    edtWifiName.setText("");
                }
            }
        });

        ivClear.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View v) {
                edtWifiPwd.setText("");
            }
        });
        btnSendWifi.setOnClickListener(this);
        if (originType == AddFragmentTabActivity.DEVICE_ADD_TYPE_AP) {
            tvWifiNum.setVisibility(View.GONE);
        } else {
            tvTips.setVisibility(View.GONE);
            tvWifiNum.setText(String.format(getString(R.string.search_wifi_device_num), list.size()));
        }
    }

    @Override
    public void onAddDeviceClick(int position) {
        bindDevice(list.get(position));
    }


    private void bindDevice(String deviceUUID) {
        showLoading();

        DeviceBinding.create().request(deviceUUID, "lan", new DeviceBinding.Callback() {
            @Override
            public void onSuccess(BindDeviceBean content) {
                hideLoading();
                if (listener != null) {
                    LogUtils.matTrackCustomKVEvent(getContext(), "device_add", "CCS");
                    listener.onSetDeviceName(content.getId(), "", content.getAuth_status(), content.getIccid(),content.getIs_notice_free_combo());
                }
            }

            @Override
            public void onError(int errorCode, String errorInfo) {
                hideLoading();
                Toast.makeText(TGApplicationBase.getApplication(), errorInfo, Toast.LENGTH_SHORT).show();
                if (listener != null) {
                    LogUtils.matTrackCustomKVEvent(getContext(), "device_add", "CCF");
                    listener.onAddDeviceFailed(AddFragmentTabActivity.ERROR_NORMAL);
                }
            }
        });
    }

    public void sendIoCtrl() {
        String wName = edtWifiName.getText().toString();
        String wPassword = edtWifiPwd.getText().toString();
        int userId = PreferenceUtil.getInt(getActivity(), CommonConstants.PRE_USER_ID);
        bind_token = DeviceWiFiConfiguration.createBindToken();
        if (userId <= 0 && !CameraHub.getInstance().isEnableLocalApConnect()) {
            String name = PreferenceUtil.getString(getActivity(), CommonConstants.PRE_USER_NAME);
            String content = String.format("uuid:%s 用户名:%s  用户id 为0", camera.uid, name);
            LogUtils.uploadLogE("app 添加", content);
        }
        if (camera != null && camera.connectionState == Camera.CONNECTION_STATE_CONNECTED) {
            camera.sendIOCtrl(AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_APLINK_SETWIFI_REQ, AVIOCTRLDEFs.EcpQrcodeContent.parseContent(wName, wPassword, userId, bind_token));
            TGThreadPool.getMainHandler().postDelayed(() -> {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    ConnectivityManager.setProcessDefaultNetwork(null);
                }
            }, 3000);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_search_connect, container, false);
        tvTips = view.findViewById(R.id.tv_search_connect_tips);
        if (originType == AddFragmentTabActivity.DEVICE_ADD_TYPE_AP || originType == AddFragmentTabActivity.DEVICE_ADD_TYPE_AP_LOCAL) {
            listView = view.findViewById(R.id.search_connect_list);
        } else {
            listView = view.findViewById(R.id.search_wifi_device_list);
        }
        llSetWifiLayout = view.findViewById(R.id.ll_search_connect_wifi);
        edtWifiName = view.findViewById(R.id.edt_search_connect_wifi_name);
        edtWifiPwd = view.findViewById(R.id.edt_search_connect_wifi_password);
        pwdCheckBox = view.findViewById(R.id.checkbox_search_connect);
        btnSendWifi = view.findViewById(R.id.btn_search_connect_send_wifi_info);
        ivClear = view.findViewById(R.id.iv_search_connect_clear);
        tvWifiNum = view.findViewById(R.id.search_wifi_num_text_view);
        return view;
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_search_connect_send_wifi_info) {
            sendIoCtrl();
            if (listener != null) {
                listener.onDeviceConnecting(bind_token, AddFragmentTabActivity.TYPE_AP);
            }
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (udpSocket != null) {
            udpSocket.stopUDPSocket();
        }
    }
}
